package com.joint.web.action.party;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.DataUtil;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.RoleService;
import com.joint.base.service.UsersService;
import com.joint.core.entity.*;
import com.joint.core.service.*;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.joda.time.DateTime;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * Created by dqf on 2015/8/26.
 */
@ParentPackage("party")
public class AjaxMoneymanagerAction extends BaseFlowAction {
   
    @Resource
    private MoneyManagerService moneyManagerService;
    @Resource
    private MoneyManagerDetailService moneyManagerDetailService;
    @Resource
    private EmployeesService employeesService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private MoneyAvgDetailService moneyAvgDetailService;
    @Resource
    private MoneyAvgService moneyAvgService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private RoleService roleService;


    private MoneyManager moneyManager;
    private List<Map<String,Object>> postArrayList;

    private int numStatus;
    private Users loginUser;
    private Company company;
    private int len;//集合长度

   private String moneyManagerDepartId;


    /**
     * 登记年月
     */
    private String recordDate;
    /**
     * 支部名称
     */
    private Department department;
    /**
     * 党费等级详情表
     */
    private List<MoneyManagerDetail> moneyManagerDetailList;
    /**
     * 累计可支配党费金额
     */
    private BigDecimal cumulativeAmountPartyMoney;


    private String viewtype;
    private String employessId;
    private Employees employees;
    private String monthPayDues;
    private String payDate;
    private String moneyManagerDetailId;
    private String departId;
    List<BigDecimal> bigDecimalList;//实际缴纳的党费
    List<Employees> employeesList;//员工信息对象


    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "moneymanager";
    }

    public String checkMonth(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        loginUser = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);

        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        List<String> stringList=Lists.newArrayList();
        if(StringUtils.isNotEmpty(recordDate)){
            for(String s:recordDate.split("-")){
                stringList.add(s.trim());
            }
            params.put("registerYear",stringList.get(0));
            params.put("registerMonth",stringList.get(1));
        }
        if(StringUtils.isNotEmpty(departId)){
            Department department=departmentService.get(departId.trim());
            params.put("department",department);
        }
        List<MoneyManager> moneyManagersList;
        if (pager.getTotalCount() > 0){
            moneyManagersList = (List<MoneyManager>) pager.getList();
        }else{
            moneyManagersList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

       if(moneyManagersList.size()>0){
           int count =moneyManagersList.size();
           data.put("count",count);
       }else{
           data.put("count",0);
       }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }
    public String listfordialog(){//查询当前登录用户所有一级部门，指定年份的档子

        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users users = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy");
        String registerYear= sdf.format(new Date());
        params.put("registerYear",registerYear);
        params.put("processState",new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Backed,FlowEnum.ProcessState.Running});

        //同一个部门，同一个职权，两个人同时拥有这个岗位，如果查询条件有创建者，a创建这个部门的记录，b就看不到了

       /* Set<Department> departments= Sets.newHashSet();
        Set<Duty> dutyList=users.getDutySet();
        loop2:for(Duty duty:dutyList){
            if(duty.getState().name().equals("Enable")){
                if(duty.getDepartment().getParent()==null){

                    if(duty.getPost().getName().equals("组织委员")==false){
                        continue loop2;
                    }
                    Department d=duty.getDepartment();
                    departments.add(d);
                }else {
                    if (duty.getPost().getName().equals("组织委员") == false) {
                        continue loop2;
                    }
                    Department department2 = duty.getDepartment().getParent();
                    departments.add(department2);
                }
            }
        }

        if(departments.size()>0){
            params.put("department",departments);
        }*/
        pager=moneyManagerService.findByPager(pager,params);
        List<MoneyManager> moneyManagerList;
        if (pager.getTotalCount() > 0){
            moneyManagerList = (List<MoneyManager>) pager.getList();
        }else{
            moneyManagerList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(MoneyManager moneyManager:moneyManagerList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",moneyManager.getId()!=null?moneyManager.getId():"");
            rMap.put("creater",moneyManager.getCreater()!=null?moneyManager.getCreater().getName():"");
            rMap.put("registerYear",moneyManager.getRegisterYear()!=null?moneyManager.getRegisterYear():"");
            rMap.put("registerMonth",moneyManager.getRegisterMonth()!=null?moneyManager.getRegisterMonth():"");
            rMap.put("department",moneyManager.getDepartment()!=null?moneyManager.getDepartment().getName():"");
            rMap.put("cumulativeAmountPartyMoney",moneyManager.getCumulativeAmountPartyMoney()!=null?moneyManager.getCumulativeAmountPartyMoney():"");
            rMap.put("state",moneyManager.getProcessState()!=null?moneyManager.getProcessState().value():"");
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }
    public String count(){

        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("processState",FlowEnum.ProcessState.Finished);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        pager=moneyManagerService.findByPagerAndProcessState(pager, user, "moneymanager", FlowEnum.ProcessState.Finished, params);
        List<MoneyManager> moneyManagerList;
        if (pager.getTotalCount() > 0){
            moneyManagerList = (List<MoneyManager>) pager.getList();
        }else{
            moneyManagerList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        List<Date> createDateArr=Lists.newArrayList();
        BigDecimal money=new BigDecimal(0);
        for(MoneyManager moneyManager:moneyManagerList){
        if(moneyManagerList.size()>0){
            for(int i=0;i<moneyManagerList.size();i++){
                createDateArr.add(moneyManagerList.get(i).getCreateDate());
            }

            Date tempDate=Collections.max(createDateArr);

                if(tempDate.equals(moneyManager.getCreateDate())){
                    money=moneyManager.getCumulativeAmountPartyMoney().add(money);
                }
            }
        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("money",money);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }
    public String list(){
        pager = new Pager(0);
        /*if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        loginUser = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        //params = getSearchFilterParams(_search,params,filters);

        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=moneyManagerService.findByPagerAndLimit(false, "moneymanager", pager, params);
            }else if(viewtype.equals("2")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=moneyManagerService.findByPagerAndFinish("moneymanager", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=moneyManagerService.findByPagerAndLimit(true, "moneymanager", pager, params);
        }

        List<MoneyManager> moneyManagersList;
        if (pager.getTotalCount() > 0){
            moneyManagersList = (List<MoneyManager>) pager.getList();
        }else{
            moneyManagersList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        //查询可用金额
        Map<String,Object> params1 = new HashMap<String,Object>();
        //params1 = getSearchFilterParams(_search,params1,filters);

        params1.put("company",com);
        params1.put("state",BaseEnum.StateEnum.Enable);
        params1.put("processState",new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
        List<MoneyAvg> moneyAvgDList=moneyAvgService.getList(params1);
        List<Date> createDateList=Lists.newArrayList();
        for(MoneyAvg moneyAvg:moneyAvgDList){
            createDateList.add(moneyAvg.getCreateDate());
        }
        MoneyAvg tempMoneyAvg=new MoneyAvg();
        for(MoneyAvg moneyAvg:moneyAvgDList){
            if(moneyAvg.getCreateDate()==Collections.min(createDateList)){
                tempMoneyAvg=moneyAvg;
            }
        }
        List<MoneyAvgDetail> moneyAvgDetailList=Lists.newArrayList();
        if(tempMoneyAvg!=null){
            moneyAvgDetailList =tempMoneyAvg.getMoneyAvgDetailList();
        }

        for(MoneyManager moneyManager:moneyManagersList){

            SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
            rMap = new HashMap<String,Object>();
            rMap.put("id",moneyManager.getId()!=null?moneyManager.getId():"");
            /*if(moneyManager.getCreateDate()!=null){
                String year=new SimpleDateFormat("yyyy").format(moneyManager.getRecordDate());
                String month=new SimpleDateFormat("MM").format(moneyManager.getRecordDate());
                rMap.put("year",year);
                rMap.put("month",month);
            }else{
                rMap.put("year","");
                rMap.put("month","");
            }*/
            rMap.put("registerYear",moneyManager.getRegisterYear()!=null?moneyManager.getRegisterYear():"");
            rMap.put("registerMonth",moneyManager.getRegisterMonth()!=null?moneyManager.getRegisterMonth():"");
            rMap.put("department",moneyManager.getDepartment()!=null?moneyManager.getDepartment().getName():"");
            rMap.put("cumulativeAmountPartyMoney",moneyManager.getCumulativeAmountPartyMoney()!=null?moneyManager.getCumulativeAmountPartyMoney():"");
            if(moneyAvgDetailList!=null&&moneyAvgDetailList.size()>0){//先判断null，在判断size大小
                loop2:for(MoneyAvgDetail moneyAvgDetail:moneyAvgDetailList){
                    if(moneyManager.getDepartment()==moneyAvgDetail.getDepartment()){
                        rMap.put("departResideEnableMoney",moneyAvgDetail.getDepartResidueEnableMoney()!=null?moneyAvgDetail.getDepartResidueEnableMoney():0.00);
                        break loop2;
                    }else{
                        rMap.put("departResideEnableMoney",0.00);
                    }
                }
            } else {
                rMap.put("departResideEnableMoney",0.00);
            }
            rMap.put("state",moneyManager.getProcessState().value()!=null?moneyManager.getProcessState().value():"");
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }
    public Map getSearchFilterParams(String _search,Map<String,Object> params,String filters){
        //createAlias Key集合
        List<String> alias = new ArrayList<String>();
        if(StringUtils.isNotEmpty(_search)){
            boolean __search = Boolean.parseBoolean(_search);
            if(__search&& StringUtils.isNotEmpty(filters)){
                JSONObject filtersJson = JSONObject.fromObject(filters);
                if(StringUtils.equals(filtersJson.getString("groupOp"), "AND")){
                    //查询条件
                    JSONArray rulesJsons = filtersJson.getJSONArray("rules");
                    //遍历条件
                    for(int i=0;i<rulesJsons.size();i++){
                        JSONObject rule = rulesJsons.getJSONObject(i);
                        if(rule.has("field")&& StringUtils.isNotEmpty(rule.getString("field"))&&rule.has("data")&& StringUtils.isNotEmpty(rule.getString("data"))){
                            String field = rule.getString("field");
                            if(field.contains("_")){
                                String[] fields = field.split("_");
                                if(StringUtils.isNotEmpty(rule.getString("data"))){
                                    params.put(field.replaceAll("_", "."), rule.getString("data"));
                                }
                            }else{
                                if(StringUtils.isNotEmpty(rule.getString("data"))){
                                    switch (field){
                                        case "cumulativeAmountPartyMoney":
                                            params.put("cumulativeAmountPartyMoney", new BigDecimal(rule.getString("data")));
                                            break;
                                        default:
                                            params.put(field, rule.getString("data"));
                                    }
                                   /* if(field.equals("createDate")){
                                        params.put("createDate", com.joint.base.util.DataUtil.StringToDate(rule.getString("data")));
                                    }
                                    else {
                                        params.put(field, rule.getString("data"));
                                    }*/
                                }
                            }
                        }
                    }

                }
            }
        }

        return params;
    }
    public String read(){
        department=new Department();
        moneyManagerDetailList=Lists.newArrayList();
        if(StringUtils.isNotEmpty(keyId)) {
            loginUser=usersService.getLoginInfo();
            moneyManager = moneyManagerService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);

            //支部名称
            if(moneyManager.getDepartment()!=null){
                department=moneyManager.getDepartment();
            }
            //缴费详情表
            if(moneyManager.getMoneyManagerDetailList()!=null){
                moneyManagerDetailList=moneyManager.getMoneyManagerDetailList();
            }



        }
        return "read";
    }

    public String input(){
        department=new Department();
        moneyManagerDetailList=Lists.newArrayList();
        if (StringUtils.isNotEmpty(keyId)){

            moneyManager = moneyManagerService.get(keyId);
            loginUser=usersService.getLoginInfo();
            numStatus = workflowService.getNumStatus(keyId, loginUser);

            //支部名称
            if(moneyManager.getDepartment()!=null){
                department=moneyManager.getDepartment();
            }
            //缴费详情表
            if(moneyManager.getMoneyManagerDetailList()!=null){
                moneyManagerDetailList=moneyManager.getMoneyManagerDetailList();
            }


        } else {

        }
        Set<Department> departments= Sets.newHashSet();
        Users users=usersService.getLoginInfo();
        Set<Duty> dutyList=users.getDutySet();
        loop2:for(Duty duty:dutyList){
            if(duty.getState().name().equals("Enable")){
                if(duty.getDepartment().getParent()==null){

                    if(duty.getPost().getName().equals("组织委员")==false){
                        continue loop2;
                    }
                    Department d=duty.getDepartment();
                    departments.add(d);
                }else {
                    if (duty.getPost().getName().equals("组织委员") == false) {
                        continue loop2;
                    }
                    Department department2 = duty.getDepartment().getParent();
                    departments.add(department2);
                }
            }

        }
        departId="";
        for(Department department:departments){
            departId+=department.getId()+",";
        }
        return "input";
    }

    private void setData(){
        department=new Department();
        loginUser=usersService.getLoginInfo();
        company=usersService.getLoginInfo().getCompany();
        employeesList=Lists.newArrayList();
        bigDecimalList=Lists.newArrayList();
        moneyManagerDetailList=Lists.newArrayList();
        len=0;

        if(StringUtils.isNotEmpty(keyId)){
            moneyManager = moneyManagerService.get(keyId);
        }else{
            moneyManager = new MoneyManager();
            moneyManager.setCreater(usersService.getLoginInfo());

        }
        //部门
        if(StringUtils.isNotEmpty(moneyManagerDepartId)){
            department=departmentService.get(moneyManagerDepartId);
        }
        //实际交的党费
        if(StringUtils.isNotEmpty(monthPayDues)){
            for(String s:monthPayDues.split(",")){
                BigDecimal bigDecimal=new BigDecimal(s.trim());
                bigDecimalList.add(bigDecimal);
            }
        }
        //人员信息对象
        if(StringUtils.isNotEmpty(employessId)){
            for(String s:employessId.split(",")){
                employees=employeesService.get(s.trim());
                employeesList.add(employees);
            }
        }
        len=employeesList.size();
        List<String> dateList=Lists.newArrayList();
        if(recordDate!=null){
            for(String s:recordDate.toString().split("-")){
                dateList.add(s.trim());
            }
        }
        Date date=null;
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM");
        try {
            date=sdf.parse(recordDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(date!=null) moneyManager.setRecordDate(date);
        moneyManager.setRegisterYear(dateList.get(0));
        moneyManager.setRegisterMonth(dateList.get(1));
        moneyManager.setDepartment(department);
        moneyManager.setCumulativeAmountPartyMoney(cumulativeAmountPartyMoney);
        moneyManager.setCreater(loginUser);
        moneyManager.setCompany(company);
        moneyManager.setState(BaseEnum.StateEnum.Enable);
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                moneyManager=moneyManagerService.get(keyId);
                if(StringUtils.isNotEmpty(moneyManagerDetailId)){
                    for(String s:moneyManagerDetailId.split(",")){
                        moneyManagerDetailList.add(moneyManagerDetailService.get(s.trim()));
                    }
                    for(int i=0;i<len;i++){
                        MoneyManagerDetail moneyManagerDetail=moneyManagerDetailList.get(i);
                        moneyManagerDetail.setCompany(company);
                        moneyManagerDetail.setState(BaseEnum.StateEnum.Enable);
                        moneyManagerDetail.setCreater(loginUser);
                        moneyManagerDetail.setMonthPayDues(bigDecimalList.get(i));
                        moneyManagerDetail.setEmployees(employeesList.get(i));
                        moneyManagerDetail.setMoneyManager(moneyManager);
                        moneyManagerDetailService.update(moneyManagerDetail);
                        moneyManagerDetailList.add(moneyManagerDetail);
                    }
                    moneyManager.setMoneyManagerDetailList(moneyManagerDetailList);
                    /*moneyManagerService.update(moneyManager);*/
                }else{
                    moneyManagerDetailList=moneyManager.getMoneyManagerDetailList();
                    for(MoneyManagerDetail moneyManagerDetail:moneyManagerDetailList){
                        moneyManagerDetailService.delete(moneyManagerDetail);
                    }
                    moneyManager.setMoneyManagerDetailList(null);
                    List<MoneyManagerDetail> moneyManagerDetailList2=Lists.newArrayList();
                    for(int i=0;i<len;i++){
                        MoneyManagerDetail moneyManagerDetail=new MoneyManagerDetail();
                        moneyManagerDetail.setCompany(company);
                        moneyManagerDetail.setState(BaseEnum.StateEnum.Enable);
                        moneyManagerDetail.setCreater(loginUser);
                        moneyManagerDetail.setMonthPayDues(bigDecimalList.get(i));
                        moneyManagerDetail.setEmployees(employeesList.get(i));
                        moneyManagerDetail.setMoneyManager(moneyManager);
                        moneyManagerDetailService.save(moneyManagerDetail);
                        moneyManagerDetailList2.add(moneyManagerDetail);
                    }
                    moneyManager.setMoneyManagerDetailList(moneyManagerDetailList2);
                    /*moneyManagerService.update(moneyManager);*/
                }
                moneyManagerService.update(moneyManager);


            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                String id=moneyManagerService.save(moneyManager, "moneymanager", various);

                moneyManager=moneyManagerService.get(id);
                for(int i=0;i<len;i++){
                    MoneyManagerDetail moneyManagerDetail=new MoneyManagerDetail();
                    moneyManagerDetail.setCompany(company);
                    moneyManagerDetail.setState(BaseEnum.StateEnum.Enable);
                    moneyManagerDetail.setCreater(loginUser);
                    moneyManagerDetail.setMonthPayDues(bigDecimalList.get(i));
                    moneyManagerDetail.setEmployees(employeesList.get(i));
                    moneyManagerDetail.setMoneyManager(moneyManager);
                    moneyManagerDetailService.save(moneyManagerDetail);
                    moneyManagerDetailList.add(moneyManagerDetail);
                }
                moneyManager.setMoneyManagerDetailList(moneyManagerDetailList);
                moneyManagerService.update(moneyManager);
            }



        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        if(StringUtils.isNotEmpty(keyId)){
            moneyManager=moneyManagerService.get(keyId);
            if(StringUtils.isNotEmpty(moneyManagerDetailId)){
                for(String s:moneyManagerDetailId.split(",")){
                    moneyManagerDetailList.add(moneyManagerDetailService.get(s.trim()));
                }
                for(int i=0;i<len;i++){
                    MoneyManagerDetail moneyManagerDetail=moneyManagerDetailList.get(i);
                    moneyManagerDetail.setCompany(company);
                    moneyManagerDetail.setState(BaseEnum.StateEnum.Enable);
                    moneyManagerDetail.setCreater(loginUser);
                    moneyManagerDetail.setMonthPayDues(bigDecimalList.get(i));
                    moneyManagerDetail.setEmployees(employeesList.get(i));
                    moneyManagerDetail.setMoneyManager(moneyManager);
                    moneyManagerDetailService.update(moneyManagerDetail);
                    moneyManagerDetailList.add(moneyManagerDetail);
                }
                moneyManager.setMoneyManagerDetailList(moneyManagerDetailList);
                moneyManagerService.update(moneyManager);
            }else{
                List<MoneyManagerDetail> moneyManagerDetailList1=moneyManager.getMoneyManagerDetailList();//存放子表的临时表
                for(MoneyManagerDetail moneyManagerDetail:moneyManagerDetailList1){
                    moneyManagerDetailService.delete(moneyManagerDetail);
                }
                moneyManager.setMoneyManagerDetailList(null);
                for(int i=0;i<len;i++){
                    MoneyManagerDetail moneyManagerDetail=new MoneyManagerDetail();
                    moneyManagerDetail.setCompany(company);
                    moneyManagerDetail.setState(BaseEnum.StateEnum.Enable);
                    moneyManagerDetail.setCreater(loginUser);
                    moneyManagerDetail.setMonthPayDues(bigDecimalList.get(i));
                    moneyManagerDetail.setEmployees(employeesList.get(i));
                    moneyManagerDetail.setMoneyManager(moneyManager);
                    moneyManagerDetailService.save(moneyManagerDetail);
                    moneyManagerDetailList.add(moneyManagerDetail);
                }
                moneyManager.setMoneyManagerDetailList(moneyManagerDetailList);
                moneyManagerService.update(moneyManager);
            }
        } else {
            moneyManagerService.save(moneyManager);
            for(int i=0;i<len;i++){
                MoneyManagerDetail moneyManagerDetail=new MoneyManagerDetail();
                moneyManagerDetail.setCompany(company);
                moneyManagerDetail.setState(BaseEnum.StateEnum.Enable);
                moneyManagerDetail.setCreater(loginUser);
                moneyManagerDetail.setMonthPayDues(bigDecimalList.get(i));
                moneyManagerDetail.setEmployees(employeesList.get(i));
                moneyManagerDetail.setMoneyManager(moneyManager);
                moneyManagerDetailService.save(moneyManagerDetail);
                moneyManagerDetailList.add(moneyManagerDetail);
            }
            moneyManager.setMoneyManagerDetailList(moneyManagerDetailList);
            moneyManagerService.update(moneyManager);
        }


        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        var2.put("initDuty", curDutyId);
        ArrayList<String> list = new ArrayList<String>();

        Set<Duty> dutySet= null;
        ArrayList<Department> departmentArrayList=null;
        dutySet=usersService.getLoginInfo().getDutySet();

        /*loop1:for(Duty duty:dutySet){//当前登录用户的所有职责（duty）
            // LogUtil.info("duty:"+duty.getId());
            Post post = duty.getPost();//根据当前登录用户的职责，得到当前登陆用户的岗位
            if(StringUtils.equals(post.getName(),"组织委员")  == false){
                continue;//进入当前登录人的下一个职权
            }
            Department dept = duty.getDepartment().getParent();//根据当前登陆人的职责，得到当前人的部门的上级部门
            if (dept == null) {//上级部门为空的话，进入当前人的下一个职责
                continue;
            }
            Set<Power> powers = dept.getPowerSet();//获取当前登陆人的职责，得到部门的部门的职权集合
            loop2:for(Power power:powers){//遍历姥姥级部门下的所有职权
                //   LogUtil.info("power:"+power.getId());
                Post post1 = power.getPost();
                if(post1.getName().equals("支部书记") == true) {
                    List<Users> usersList=dutyService.getPersons(dept, post1);//更具岗位对象获取该部门下的指定岗位下的 所有人
                    for(Users users1:usersList){
                        LogUtil.info("userName:"+users1.getName());
                        list.add(users1.getId());
                    }
                    break loop1;
                }
            }
        }*/
        if(org.apache.commons.lang.StringUtils.isNotEmpty(moneyManagerDepartId)){
            department=departmentService.get(moneyManagerDepartId);
            Set<Power> powers = department.getPowerSet();
            for(Power power:powers){
                Post post1 = power.getPost();
                if(post1.getName().equals("支部书记")==true){
                    List<Users> usersList=dutyService.getPersons(department, post1);
                    for(Users users1:usersList){
                        list.add(users1.getId());
                    }
                }
            }
            var2.put("approvers",list);
        }
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                moneyManagerService.approve(moneyManager, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
               moneyManagerService.commit(moneyManager, "moneymanager", var1, var2, curDutyId);/*返回文档的iD*/


            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批
    public String approve1(){
        moneyManager = moneyManagerService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        //var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                moneyManagerService.approve(moneyManager, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
                Task overtask = workflowService.getCurrentTask(keyId);
                if(runtimeService.getVariable(overtask.getExecutionId(),"nrOfCompletedInstances")==null){
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 2);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }
    // 会签
    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";

        moneyManager = moneyManagerService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("curDutyId", curDutyId);
        try {
            moneyManagerService.approve(moneyManager, FlowEnum.ProcessState.Finished, var2, curDutyId, comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        moneyManager = moneyManagerService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        //  var2.put("curDutyId", curDutyId);
        try {
            moneyManagerService.approve(moneyManager, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            moneyManager = moneyManagerService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("moneymanager");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            moneyManagerService.reject(moneyManager, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            moneyManager = moneyManagerService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("moneymanager");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            moneyManagerService.deny(moneyManager, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }



    public MoneyManager getMoneyManager() {
        return moneyManager;
    }

    public void setMoneyManager(MoneyManager moneyManager) {
        this.moneyManager = moneyManager;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }


    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }


    public String getViewtype() {


        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public List<Map<String, Object>> getPostArrayList() {
        return postArrayList;
    }

    public void setPostArrayList(List<Map<String, Object>> postArrayList) {
        this.postArrayList = postArrayList;
    }

    public String getMoneyManagerDepartId() {
        return moneyManagerDepartId;
    }

    public void setMoneyManagerDepartId(String moneyManagerDepartId) {
        this.moneyManagerDepartId = moneyManagerDepartId;
    }

    public String getRecordDate() {
        return recordDate;
    }

    public void setRecordDate(String recordDate) {
        this.recordDate = recordDate;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public BigDecimal getCumulativeAmountPartyMoney() {
        return cumulativeAmountPartyMoney;
    }

    public void setCumulativeAmountPartyMoney(BigDecimal cumulativeAmountPartyMoney) {
        this.cumulativeAmountPartyMoney = cumulativeAmountPartyMoney;
    }

    public List<MoneyManagerDetail> getMoneyManagerDetailList() {
        return moneyManagerDetailList;
    }

    public void setMoneyManagerDetailList(List<MoneyManagerDetail> moneyManagerDetailList) {
        this.moneyManagerDetailList = moneyManagerDetailList;
    }

   

   
    public String getMonthPayDues() {
        return monthPayDues;
    }

    public void setMonthPayDues(String monthPayDues) {
        this.monthPayDues = monthPayDues;
    }

    public String getPayDate() {
        return payDate;
    }

    public void setPayDate(String payDate) {
        this.payDate = payDate;
    }

    public String getMoneyManagerDetailId() {
        return moneyManagerDetailId;
    }

    public void setMoneyManagerDetailId(String moneyManagerDetailId) {
        this.moneyManagerDetailId = moneyManagerDetailId;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public String getEmployessId() {
        return employessId;
    }

    public void setEmployessId(String employessId) {
        this.employessId = employessId;
    }

    public Employees getEmployees() {
        return employees;
    }

    public void setEmployees(Employees employees) {
        this.employees = employees;
    }
}


